import { defineConfig, loadEnv, ConfigEnv, UserConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import { wrapperEnv } from "./src/utils/index";
import viteCompression from "vite-plugin-compression";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import zipPack from "vite-plugin-zip-pack";
console.log(loadEnv("development", process.cwd()).VITE_src);

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, process.cwd());
  const viteEnv = wrapperEnv(env);
  return {
    plugins: [
      vue(),
      // 开启文件压缩：支持的类型有html,js,css,svg,json
      viteEnv.VITE_BUILD_GZIP &&
      viteCompression({
        verbose: true, //控制台显示压缩信息
        disable: false,
        threshold: 10240, //默认是1501
        algorithm: "gzip",
        ext: ".gz",
      }),

      // * 使用 svg 图标
      createSvgIconsPlugin({
        iconDirs: [resolve(process.cwd(), "src/assets/svgs")],
        symbolId: "icon-[dir]-[name]",
      }),
      // 自动导入
      AutoImport({
        imports: ["vue", "vue-router", "pinia"],
        dts: "src/auto-import.d.ts",
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      zipPack({inDir:"dist/source",outDir:"dist",outFileName:"dist.zip"}),
    ],
    server: {
      host: "0.0.0.0",
      port: viteEnv.VITE_PORT,
      open: viteEnv.VITE_OPEN,

      proxy: {
        "/api": {
          target: viteEnv.VITE_API,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, "")
        },
      },
    },
    resolve: {
      // 别名配置
      alias: {
        "@": resolve(__dirname, "./src"),
      },
    },
    css: {
      // 对css预处理器的一些配置
      preprocessorOptions: {
        scss: {
          additionalData: `@import"@/styles/var.scss";`,
        },
      },
      devSourcemap: true,
    },
    build: {
      // 配置rollup的构建策略
      rollupOptions: {
        // 控制输出
        output: {
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          // 静态资源命名（ext表示文件后缀名）
          assetFileNames: "[hash].[name].[ext]",
          // 模块拆分
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
        },
      },
      outDir:"dist/source",
      assetsInlineLimit: 4096,
      sourcemap: false,
    },
  };
});
